# -*- coding: utf-8 -*-
from flask import request,g
from application import app,db
import json
from common.libs.Helper import get_current_date
from common.models.log.AppAccessLog import AppAccessLog
from common.models.log.AppErrorLog import AppErrorLog

class LogLibs():
    @staticmethod
    def addAccessLog():
        app_access_log = AppAccessLog()
        app_access_log.target_url = request.url
        app_access_log.referer_url = request.referrer
        app_access_log.ip = request.remote_addr
        app_access_log.query_params = json.dumps(  request.values.to_dict() )
        if 'current_user' in g and g.current_user is not None:
            app_access_log.uid = g.current_user.uid
        app_access_log.ua = request.headers.get( "User-Agent" )
        app_access_log.created_time = get_current_date()
        db.session.add( app_access_log )
        db.session.commit( )
        return True

    @staticmethod
    def addErrorLog( content ):
        if 'favicon.ico' in request.url:
            return
        app_error_log = AppErrorLog()
        app_error_log.target_url = request.url
        app_error_log.referer_url = request.referrer
        app_error_log.query_params = json.dumps(request.values.to_dict())
        app_error_log.content = content
        app_error_log.created_time = get_current_date()
        db.session.add(app_error_log)
        db.session.commit()
        return True